import axios from 'axios'

export default {
  namespaced: true,
  state () {
    return {
      list: []
    }
  },
  mutations: {
    getList (state, newList) {
      state.list = newList
    },
    updatedCount (state, obj) {
      // console.log(obj.count)

      state.list.find(item => item.id === obj.id).count = obj.newCount
    }
  },
  actions: {
    async getListAsync (context) {
      const res = await axios({
        url: 'http://localhost:3000/cart'
      })
      // console.log(res.data)
      context.commit('getList', res.data)
    },
    async changeCount (context, obj) {
      // console.log(typeof obj.newCount)
      if (obj.newCount < 1) return
      await axios({
        url: 'http://localhost:3000/cart/' + obj.id,
        method: 'patch',
        data: {
          count: obj.newCount
        }
      })
      context.commit('updatedCount', obj)
    }
  },
  getters: {
    getTotal (state) {
      return state.list.reduce((sum, item) => (sum + item.count), 0)
    },
    getTotalPrice (state) {
      return state.list.reduce((sum, item) => (sum + item.count * item.price), 0)
    }
  }
}
